#include "mode_thawing.h"
#include "actuator_control.h"
#include <stdio.h>

// 解冻模式状态
static struct {
    uint32_t start_time;
    bool compressor_started;
    uint32_t compressor_delay_end;
    const SystemConfig *config;  // 配置指针
} thawing_state;

// 初始化解冻模式
void mode_thawing_init(const SystemConfig *config) {
    if (config) {
        thawing_state.config = config;
    }
    
    // 初始化状态变量
    thawing_state.start_time = 0;
    thawing_state.compressor_started = false;
    thawing_state.compressor_delay_end = 0;
}

// 进入解冻模式
void mode_thawing_enter(void) {
    printf("Entering thawing mode\n");
    
    // 记录开始时间
    thawing_state.start_time = get_system_time_sec();
    thawing_state.compressor_started = false;
    thawing_state.compressor_delay_end = get_system_time_ms() + 8000;  // 8秒延迟
    
    // 立即开启冷冻缸制热阀
    actuator_set_freezing_heater_valve(true);
}

// 退出解冻模式
void mode_thawing_exit(void) {
    printf("Exiting thawing mode\n");
    
    // 关闭相关设备
    actuator_set_compressor(false);
    actuator_set_freezing_heater_valve(false);
}

// 处理解冻模式逻辑
ModeStatus mode_thawing_process(void) {
    uint32_t current_time_ms = get_system_time_ms();
    uint32_t current_time_sec = get_system_time_sec();
    
    // 检查是否超过解冻时间
    if (current_time_sec - thawing_state.start_time > thawing_state.config->thawing_time) {
        printf("Thawing completed (reached %d minutes)\n", 
               thawing_state.config->thawing_time / 60);
        return MODE_STATUS_COMPLETE;
    }
    
    // 处理压缩机延迟启动
    if (!thawing_state.compressor_started && current_time_ms >= thawing_state.compressor_delay_end) {
        actuator_set_compressor(true);
        thawing_state.compressor_started = true;
        printf("Compressor started after 8s delay\n");
    }
    
    return MODE_STATUS_RUNNING;  // 继续运行
}
    